package com.kexin.coupon.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kexin.common.exception.WebException;
import com.kexin.coupon.entity.Coupon;
import com.kexin.coupon.mapper.CouponMapper;
import com.kexin.coupon.service.ICouponOrderService;
import com.kexin.coupon.service.ICouponService;

/**
 * 卡券表 服务实现类
 * @author ao
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

	@Autowired
	private ICouponOrderService couponOrderService;

	@Override
	public Page<Coupon> queryList(String couponName, Integer state, Integer current, Integer size) {
		QueryWrapper<Coupon> query = Wrappers.query();
		query.like(StringUtils.isNotBlank(couponName), "coupon_name", couponName);
		query.eq(state!=null, "state", state);
		query.eq("shelve", "1");
		query.orderByDesc("create_time");
		if (current==null) {
			current = 1;
		}
		if (size==null) {
			size = 10;
		}
		return page(new Page<Coupon>(current, size), query);
	}

	@Override
	public Coupon getOne(Integer id) {
		return getById(id);
	}

	@Override
	public void updateCount(Integer couponId, Integer userId, int count, int type) {
		if (couponId==null) {
			throw new WebException("卡券id为空");
		}
		synchronized (couponId.toString().intern()) {
			Coupon coupon = getById(couponId);
			if (coupon==null) {
				throw new WebException("卡券信息不存在");
			}
			if (count<=0) {
				throw new WebException("更新数量必须为正整数");
			}
			//总库存量
			Integer totalCount = coupon.getTotalCount();
			//已生成卡券数量， 总库存量-已生成卡券数量=可申领卡券数量
			Integer usedCount = coupon.getUsedCount();
			//单次申领最大数
			//Integer applyMaxNum = coupon.getApplyMaxNum();
			//每人限购，-1不限购
			Integer buyMax = coupon.getBuyMax();
			//被未支付订单占用的库存数量（被锁定库存量）
			Integer unpaidCount = coupon.getUnpaidCount();
			//可申领卡券数量=总库存量-已生成卡券数量
			Integer allowCount = totalCount-usedCount;
			//剩余可买数量=可申领卡券数量-被未支付订单占用的库存数量
			Integer allowBuyCount = allowCount-unpaidCount;
			
			if (type==1) {
				if (allowCount<=0) {
					throw new WebException("此卡券已申领完");
				}
				if (allowBuyCount<=0) {
					throw new WebException("此卡券已申领完，暂时还有"
							+unpaidCount+"张未支付，请稍后再试");
				}
				if (allowBuyCount-count<=0) {
					throw new WebException("此卡券已申领完，暂时还有"
							+unpaidCount+"张未支付，请减少数量或稍后再试");
				}
				/*if (couponOrderService.getUserBuyedCount(
						userId, coupon.getCouponCode(), "0")>0) {
					throw new WebException("此卡券你已申领但未支付，请先支付，请勿重复下单");
				}*/
				int userBuyedCount = couponOrderService.getUserBuyedCount(
						userId, coupon.getCouponCode(), "1");
				if (buyMax==0) {
					throw new WebException("此卡券每人限购0件，无法购买卡券");
				} else if (buyMax>0&&count+userBuyedCount>buyMax) {
					int notCount = buyMax-userBuyedCount;
					if (notCount>0) {
						throw new WebException("此卡券每人限购"+buyMax+"件，你已经购买了"
								+userBuyedCount+"件，最多还能购买"+notCount+"件");
					} else {
						throw new WebException("此卡券每人限购"+buyMax+"件，你已经购买了"
								+userBuyedCount+"件，不能再买了");
					}
				}
			}
			
			UpdateWrapper<Coupon> update = Wrappers.update();
			update.eq("id", couponId);
			
			//1未支付订单锁定库存，2取消未支付订单释放库存，3已支付订单扣减库存，4退款订单回滚库存
			switch (type) {
			case 1:
				//增加被未支付订单占用的库存数量
				update.setSql("unpaid_count = unpaid_count+"+count);
				break;
			case 2:
				//回滚被未支付订单占用的库存数量
				update.setSql("unpaid_count = unpaid_count-"+count);
				break;
			case 3:
				//回滚被未支付订单占用的库存数量
				update.setSql("unpaid_count = unpaid_count-"+count);
				//增加已生成卡券数量
				update.setSql("used_count = used_count+"+count);
				break;
			case 4:
				//回滚已生成卡券数量
				update.setSql("used_count = used_count-"+count);
				break;
			default:
				throw new WebException("无此类型[type="+type+"]");
			}
			//更新数据库
			update(update);
		}
	}

}
